package com.lbx.controller;

import com.lbx.entity.Books;
import com.lbx.service.BooksService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;

/**
 * @author 吕兵星
 * @date 2020/10/23 23:13
 */
@Controller
public class BooksController {
    @Autowired
    private BooksService booksService;
    @GetMapping(value = "/select/{id}")
    public String selectOne(@PathVariable("id") int id, Model model){
        Books book = booksService.selectBook(id);
        if (book==null){
            model.addAttribute("msg","没有找到");
        }
        model.addAttribute("book",book);
        return "books" ;
    }
    @PostMapping("/update")
    public String updateOne(Books books, Model model){

        int i = booksService.updateBook(books);
        if (i>0){
            model.addAttribute("msg","成功更新了"+i+"个book");
        }else {
            model.addAttribute("msg","更新了失败,更新了"+i+"个");

        }
        return "success" ;
    }
    @GetMapping(value = "/delete/{id}")
    public String deleteOne(@PathVariable("id") int id, Model model){
        int i = booksService.deleteBook(id);
        if (i>0){
            model.addAttribute("msg","成功删除了"+i+"个book");
        }else {
            model.addAttribute("msg","删除失败,删除了"+i+"个");

        }
        return "success" ;
    }
    @PostMapping(value = "/add")
    public String addOne(Books books, Model model){
        int i = booksService.addBook(books);
        if (i>0){
            model.addAttribute("msg","成功添加了"+i+"个book");
        }else {
            model.addAttribute("msg","添加失败,添加了"+i+"个");

        }
        return "redirect:/findAll" ;
    }
    @GetMapping(value = "/findAll")
    public String findAll(Model model){
        List<Books> books = booksService.findAll();
        model.addAttribute("books",books);
        model.addAttribute("msg","当前总共有"+books.size()+"本书:");

        return "books" ;
    }
}
